<template>
  <div class="music-platform">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="nav-container">
        <div class="logo">
          <img src="@/assets/logo/logo.svg" alt="KiKi音乐" class="logo-img" />
          <span class="logo-text">KiKi音乐</span>
        </div>

        <el-menu
          :default-active="activeIndex"
          class="nav-menu"
          mode="horizontal"
          background-color="#252525"
          text-color="#fff"
          active-text-color="#ff4e4e"
          @select="handleSelect"
        >
          <el-menu-item index="ranking">排行榜</el-menu-item>
          <el-menu-item index="home">猜你喜欢</el-menu-item>
          <el-menu-item index="singers">歌手</el-menu-item>
          <el-menu-item index="albums">专辑</el-menu-item>
        </el-menu>

        <div class="right-section">
          <div class="search-section">
            <el-input
              :placeholder="computedPlaceholder"
              prefix-icon="el-icon-search"
              v-model="searchKeyword"
              class="search-input"
              @keyup.enter.native="handleSearch"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="handleSearch"
              ></el-button>
            </el-input>
          </div>
          <el-dropdown class="user-dropdown">
            <span class="el-dropdown-link">
              <image-preview :src="userAvatar" :width="20" :height="20" />
              <!-- <el-avatar :size="32" :src="userAvatar"></el-avatar> -->
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                ><router-link :to="{ name: 'customerInfo' }"
                  >个人中心</router-link
                ></el-dropdown-item
              >
              <el-dropdown-item>
                <router-link :to="{ name: 'Favorite' }">我的收藏</router-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <router-link :to="{ name: 'History' }">播放历史</router-link>
              </el-dropdown-item>
              <!-- <el-dropdown-item>
                <router-link :to="{ name: 'Test' }">test</router-link>
              </el-dropdown-item> -->
              <el-dropdown-item
                ><div @click="logout">退出登录</div></el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 欢迎文本 -->
    <br />
    <br />
    <div class="welcome-text">
      <h1>欢迎来到 KiKi 音乐平台</h1>
      <p>在这里，你可以找到你喜欢的音乐、歌手和专辑，尽情享受音乐的魅力！</p>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <section id="ranking" class="content-section">
        <h1>排行榜</h1>
        <p>查看当前最热门的歌曲，了解音乐趋势。</p>
        <div class="ranking-container">
          <el-table
            :data="hotSongList"
            style="width: 100%"
            class="custom-ranking-table"
          >
            <el-table-column label="排名" width="100">
              <template slot-scope="scope">
                <div class="rank-icon">
                  <img
                    v-if="scope.$index === 0"
                    src="@/assets/icons/top1.png"
                    alt="Top 1"
                  />
                  <img
                    v-else-if="scope.$index === 1"
                    src="@/assets/icons/top2.png"
                    alt="Top 2"
                  />
                  <img
                    v-else-if="scope.$index === 2"
                    src="@/assets/icons/top3.png"
                    alt="Top 3"
                  />
                  <span v-else>{{ scope.$index + 1 }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="songName" label="歌曲" width="300">
            </el-table-column>
            <el-table-column
              prop="singer"
              label="歌手"
              width="200"
            ></el-table-column>
            <el-table-column
              prop="playCount"
              label="播放次数"
            ></el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-video-play"
                  @click="handlePlay(scope.row)"
                  >播放</el-button
                >
                <el-button size="mini" type="text" icon="el-icon-download"
                  ><a :href="scope.row.fileUrl" download>下载</a></el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </section>

      <section id="home" class="content-section">
        <h1>猜你喜欢</h1>
        <p>根据你的喜好推荐的歌曲，快来听听吧！</p>
        <div class="recommend-type" v-if="recommendSongs.length > 0">
          <el-tag
            :type="recommendType === 'online' ? 'success' : 'warning'"
            effect="dark"
          >
            {{ recommendType === "online" ? "实时推荐" : "离线推荐" }}
          </el-tag>
        </div>
        <div class="card-container">
          <el-card
            v-for="song in recommendSongs"
            :key="song.songId"
            class="music-card"
          >
            <img :src="song.imgUrl" class="card-image" />

            <div class="card-title">{{ song.songName }}</div>
            <div class="card-desc">{{ song.singer }}</div>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-video-play"
              @click="handlePlay(song)"
              >播放</el-button
            >
          </el-card>
        </div>
      </section>

      <section id="singers" class="content-section">
        <h1>热门歌手分类</h1>
        <p>了解当前最受欢迎的歌手，发现更多音乐。</p>
        <div class="singer-container">
          <el-card
            v-for="category in singerCategoryList"
            :key="category.categoryId"
            class="singer-card"
            shadow="hover"
          >
            <div
              class="singer-card-content"
              @click="handleSingerClick(category.categoryName)"
            >
              <div class="singer-image">
                <img
                  :src="require(`@/assets/images/${category.categoryName}.jpg`)"
                  :alt="category.categoryName"
                />
              </div>
              <div class="singer-name">{{ category.categoryName }}</div>
              <div class="singer-desc">点击查看详情</div>
            </div>
          </el-card>
        </div>
      </section>

      <section id="albums" class="content-section">
        <h1>最新专辑</h1>
        <p>探索最新发布的专辑，发现新音乐。</p>
        <div class="album-container">
          <el-card
            v-for="album in albumList"
            :key="album.albumId"
            class="album-card"
          >
            <div
              class="album-info"
              @click="handleAlbumClick(album.albumId, album.imgUrl)"
            >
              <image-preview :src="album.imgUrl" :width="170" :height="110" />
              <br />
              <div class="album-title">{{ album.albumName }}</div>
              <div class="album-artist">{{ album.singer }}</div>
              <div class="album-artist">{{ album.description }}</div>
            </div>
          </el-card>
        </div>
      </section>
    </div>
    <div>
      <div v-if="showDialog" class="dialog">
        <h2>选择你喜欢的音乐类型</h2>
        <div class="tags">
          <span
            v-for="tag in musicType"
            :key="tag"
            :class="['tag', { selected: selectedTypes.includes(tag) }]"
            @click="toggleTag(tag)"
          >
            {{ tag }}
          </span>
        </div>
        <button @click="submitSelection">确认选择</button>
        <button @click="showDialog = false">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import { getSingerCategoryList } from "@/api/singer_category/singer_category";
import { listSinger } from "@/api/singer/singer";
import { listAlbum } from "@/api/album/album";
import { addHistory } from "@/api/history/history";
import {
  getHotSongList,
  getMusicType,
  addLikeType,
  getLikeTypeMusic,
  getOnLineRecommendSongs,
  getOffLineRecommendSongs,
} from "@/api/song/song";
import { getUserProfile, getUserLikeType } from "@/api/system/user";
export default {
  name: "MusicPlatform",
  data() {
    return {
      singerCategoryList: [],
      likeType: [],
      showDialog: false,
      musicType: [],
      selectedTypes: [],
      recommendSinger: [],
      recommendSongs: [],
      recommendType: "",
      singerList: [],
      albumList: [],
      activeIndex: "",
      searchKeyword: "",
      userAvatar: "",
      currentSong: {
        name: "",
        artist: "",
        cover: "",
      },
      playProgress: 0,
      currentTime: "00:00",
      totalTime: "00:00",
      hotSongList: [],
    };
  },
  computed: {
    computedPlaceholder() {
      return this.recommendSinger.length > 0
        ? `${this.recommendSinger[0]}`
        : "搜索音乐、歌手、歌单";
    },
  },
  created() {
    this.handleSelect("ranking");
    // 根据当前路由设置激活的菜单项
    const path = this.$route.path.split("/")[1];
    this.activeIndex = "ranking";
    this.getHotSongList();
    this.getAlbumList();
    this.getSingerList();
    this.getSingerCategoryList();
    this.getUser();
    //获取用户喜欢的音乐类型（新用户开启选择标签）
    this.getUserLikeType();
    //获取所有的key值，然后抽取其中key为数字的所有key值
    const keys = Object.keys(localStorage);
    const filteredKeys = keys.filter((key) => !isNaN(key));

    // 使用Promise链式调用确保执行顺序
    if (filteredKeys.length !== 0) {
      // 有用户行为数据，执行实时推荐
      this.getOnLineRecommendSongs()
        .then(() => {})
        .catch((error) => {});
    } else {
      // 没有用户行为数据，先执行离线推荐
      this.getOffLineRecommendSongs()
        .then(() => {
          // 新用户，离线推荐暂时为空，执行冷启动推荐
          if (localStorage.getItem("recommendSongsLength") == 0) {
            console.log("执行冷启动推荐(即获取喜好类型)");
            return this.getLikeTypeMusic();
          }
        })
        .then(() => {})
        .catch(() => {});
    }
  },
  methods: {
    getLikeTypeMusic() {
      return getLikeTypeMusic(localStorage.getItem("userId")).then((res) => {
        console.log("执行了喜好推荐", res);
        this.recommendSongs = res;
        return res;
      });
    },

    //获取离线推荐歌曲
    getOffLineRecommendSongs() {
      return getOffLineRecommendSongs(localStorage.getItem("userId")).then(
        (res) => {
          console.log("执行了离线推荐", res);
          this.recommendSongs = res;
          this.recommendType = "offline";
          if (this.recommendSongs.length === 0) {
            console.log("新用户离线推荐为空，执行冷启动");
            localStorage.setItem("recommendSongsLength", 0);
          }
          return res;
        }
      );
    },

    //获取实时推荐歌曲
    getOnLineRecommendSongs() {
      //获取所有的key值，然后抽取其中key为数字的所有key值
      const keys = Object.keys(localStorage);
      const filteredKeys = keys.filter((key) => !isNaN(key));
      const userActionList = [];
      //获取所有数字key对应的值，添加到userActionList数组中
      filteredKeys.forEach((key) => {
        userActionList.push(JSON.parse(localStorage.getItem(key)));
      });
      return getOnLineRecommendSongs(userActionList).then((res) => {
        console.log("执行了实时推荐", res);
        this.recommendSongs = res;
        this.recommendType = "online";
        return res;
      });
    },

    /**
     * 获取并判断用户喜好标签
     */
    getUserLikeType() {
      getUserLikeType(localStorage.getItem("userId")).then((res) => {
        this.likeType = res;
        if (this.likeType[0] === null) {
          this.showDialog = true;
          getMusicType().then((res) => {
            this.musicType = res;
          });
        }
      });
    },
    toggleTag(tag) {
      const index = this.selectedTypes.indexOf(tag);
      if (index === -1) {
        this.selectedTypes.push(tag);
      } else {
        this.selectedTypes.splice(index, 1);
      }
    },
    submitSelection() {
      console.log("用户选择的音乐类型:", this.selectedTypes);
      // 将数据添加到指定的用户中
      const data = {
        userId: localStorage.getItem("userId"),
        likeType: JSON.stringify(this.selectedTypes),
      };
      // 发送请求
      addLikeType(data).then((res) => {
        //获取res列表中的前十条数据
        this.recommendSongs = res.slice(0, 10);
        // console.log("添加成功", res);
        this.loading = false;
        this.$message({
          message: "添加成功",
          type: "success",
        });
      });
      this.showDialog = false;
    },

    handlePlay(row) {
      // console.log("打印", row);
      const data = {
        songId: row.songId,
        userId: localStorage.getItem("userId"),
      };
      //记录用户播放次数
      addHistory(data).then((res) => {});
      //添加用户的行为信息到本地存储
      const index = localStorage.getItem("index");
      localStorage.removeItem("index");

      const userActionData = JSON.stringify({
        userId: localStorage.getItem("userId"),
        songId: row.songId,
        action: "play",
      });
      localStorage.setItem(parseInt(index) + 1, userActionData);

      //index加一
      localStorage.setItem("index", parseInt(index) + 1);

      const songIds = [];
      this.hotSongList.forEach((song) => {
        songIds.push(song.songId);
      });
      //搜索当前歌曲在数组中的索引位置
      const currentSongIndex = songIds.indexOf(row.songId);
      this.$router.push({
        path: "/player",
        query: {
          currentSongIndex: currentSongIndex,
          songIds: songIds,
        },
      });
    },
    //获取用户信息
    getUser() {
      getUserProfile()
        .then((response) => {
          this.user = response.data;
          this.userAvatar = response.data.avatar;
        })
        .catch((error) => {
          console.error("获取用户信息失败:", error);
        });
    },
    // 获取热门歌曲列表
    getHotSongList() {
      getHotSongList().then((res) => {
        this.hotSongList = res;
        //按照播放次数排序
        this.hotSongList.sort((a, b) => b.playCount - a.playCount);
        // 截取前10条
        this.hotSongList = this.hotSongList.slice(0, 10);
      });
    },

    //歌手模块点击事件
    handleSingerClick(keyword) {
      //传递关键词,在进行页面路由跳转
      this.$router.push({
        path: "/singerList",
        query: {
          keyword: keyword,
        },
      });
    },

    getSingerCategoryList() {
      getSingerCategoryList().then((res) => {
        // console.log("歌手类型列表", res);
        this.singerCategoryList = res;
      });
    },

    /** 查询歌手基础信息列表 */
    getSingerList() {
      this.loading = true;
      listSinger(this.queryParams).then((response) => {
        this.singerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    handleAlbumClick(albumId, imgUrl) {
      this.$router.push({
        name: "Albums",
        query: {
          albumId: albumId,
          //图片
          imgUrl: imgUrl,
        },
      });
    },
    // 获取专辑列表
    getAlbumList() {
      listAlbum().then((response) => {
        this.albumList = response;
      });
    },
    //退出登录
    async logout() {
      this.$confirm("确定注销并退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //清除localStorage中的信息
          localStorage.clear();
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/";
          });
        })
        .catch(() => {});
    },
    handleSelect(key) {
      this.activeIndex = key;
      // 平滑滚动到对应部分
      const element = document.getElementById(key);
      if (element) {
        element.scrollIntoView({ behavior: "smooth" });
      }
    },
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.searchKeyword = this.computedPlaceholder;
      }
      this.$router.push({
        name: "Search",
        query: {
          keyword: this.searchKeyword,
        },
      });
      this.searchKeyword = "";
    },
  },
};
</script>

<style scoped>
.dialog {
  border: 1px solid #ccc;
  padding: 20px;
  background-color: #fff;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
}
.tags {
  display: flex;
  flex-wrap: wrap;
}
.tag {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 5px;
  cursor: pointer;
}
.tag.selected {
  background-color: #007bff;
  color: white;
}
.music-platform {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  background-color: #252525;
  height: 64px;
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
}

.nav-container {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 48px;
}

.logo-img {
  height: 36px;
  margin-right: 12px;
}

.logo-text {
  color: #fff;
  font-size: 22px;
  font-weight: bold;
}

.nav-menu {
  border: none;
  flex: 1;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-section {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  width: 240px;
}

:deep(.el-input-group__append) {
  background-color: #ff4e4e;
  border-color: #ff4e4e;
  color: #fff;
  padding: 0 15px;
  cursor: pointer;
}

:deep(.el-input-group__append:hover) {
  background-color: #ff6b6b;
  border-color: #ff6b6b;
}

.welcome-text {
  text-align: center;
  margin: 20px 0;
  background-color: #eaeaea; /* 背景颜色 */
  padding: 20px; /* 内边距 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影 */
}

.main-content {
  margin-top: 64px;
  margin-bottom: 72px;
  flex: 1;
  max-width: 1200px;
  margin: 64px auto 72px;
}

.content-section {
  background-color: #ffffff; /* 模块背景颜色 */
  padding: 20px; /* 内边距 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 阴影 */
  margin-bottom: 20px; /* 模块间距 */
}

.content-section h1 {
  color: #333; /* 标题颜色 */
}

.card-container,
.singer-container,
.album-container,
.playlist-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.music-card,
.singer-card,
.album-card,
.playlist-card {
  transition: transform 0.3s;
}

.music-card:hover,
.singer-card:hover,
.album-card:hover,
.playlist-card:hover {
  transform: translateY(-5px);
}

.card-image,
.singer-avatar,
.album-cover,
.playlist-cover {
  width: 100%;
  height: 150px;
  object-fit: cover;
  margin-bottom: 10px;
}

.card-title,
.singer-name,
.album-title,
.playlist-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.card-desc,
.singer-fans,
.album-artist,
.playlist-count {
  font-size: 14px;
  color: #666;
}

.ranking-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.singer-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.singer-card {
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.singer-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.singer-card-content {
  padding: 0;
  text-align: center;
  cursor: pointer;
  overflow: hidden;
}

.singer-image {
  width: 100%;
  height: 150px;
  overflow: hidden;
}

.singer-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.singer-card:hover .singer-image img {
  transform: scale(1.1);
}

.singer-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin: 15px 0 8px;
  padding: 0 15px;
}

.singer-desc {
  font-size: 14px;
  color: #909399;
  padding: 0 15px 15px;
}

.custom-ranking-table .el-table__header th {
  background-color: #f0f0f0;
  color: #333;
  font-weight: bold;
}

.rank-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.rank-icon img {
  width: 24px;
  height: 24px;
}

.rank-icon span {
  font-size: 16px;
  font-weight: bold;
  color: #555;
}

.song-info {
  display: flex;
  align-items: center;
}

.song-cover {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 10px;
}

.el-table .el-table__body-wrapper {
  max-height: 600px;
}

.el-table .el-table__row:hover {
  background-color: #f9f9f9;
}

.recommend-type {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.recommend-type .el-tag {
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px;
}
</style>
